#encoding: utf-8
from sqlalchemy import Column, String, ForeignKey, Integer, Boolean, DateTime,\
     create_engine, Text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import func

Base = declarative_base()
    
class WebProxyBase(Base):
    __tablename__ = 'web_proxy'
    id = Column(Integer, primary_key=True)
    ptype = Column(String(32))
    port = Column(Integer)
    user = Column(String(16))
    pwd = Column(String(16))
    stat = Column(String(16))
    

class WebProxy:
    def __init__(self, host='localhost', port=3306, database='projectdb',
                 user='root', passwd=None):
        self.database_name = database
        self.engine = create_engine('mysql+mysqlconnector://%s:%s@%s:%s/%s' % (user, passwd, host, port, database))
        Base.metadata.create_all(self.engine) 
        DBSession = sessionmaker(bind=self.engine, autocommit=True)
        self.session = DBSession()
        
    def get(self, domain):
        result = self.session.query(WebProxyBase).filter(WebProxyBase.stat=='VALID').order_by(func.random())
        if result:
            return result.one()
        else:
            return None